<?php

namespace App\Http\Services;


use App\Http\Model\Hint;
use App\Http\Model\MallMain;
use App\Http\Model\Mall;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;


/*商城service层*/

class MallMainServices extends CommonServices
{
    protected $mallMain;

    protected $UserCoolInfo = [];

    public function __construct()
    {
        parent::__construct();

        $this->mallMain = new MallMain;
    }
    /**
     * 添加楼层
     */
    public function addMain($params)
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        try {
            $checkParams = $this -> checkParams($params);
            $res = $this->mallMain -> addMain($checkParams);
            if (!$res){
                throw new \Exception("添加楼层错误");
            }

        } catch (\Exception $e) {
            $msg = $e->getMessage(). '-LINE:'. $e->getLine();
            $code = Hint::ERR_SYS_FAIL;
        }
        write_log(
            'MallMainServices'.(isCli()?'-cli':''),
            ($code!=0 ? '[ERROR]': '[INFO]') . '楼层添加',
            ['msg'=>$msg, 'params'=>$params]
        );

        return compact('code', 'msg', 'data');
    }
    /**
     * 添加楼层
     */
    public function editMain($params)
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        try {

            $checkParams = $this -> checkParams($params, 'edit');
            $res = $this->mallMain -> editMain(['id'=>$checkParams['id']], $checkParams);
            if (!$res){
                throw new \Exception("编辑楼层错误");
            }

        } catch (\Exception $e) {
            $msg = $e->getMessage(). '-LINE:'. $e->getLine();
            $code = Hint::ERR_SYS_FAIL;
        }
        write_log(
            'MallMainServices'.(isCli()?'-cli':''),
            ($code!=0 ? '[ERROR]': '[INFO]') . '楼层编辑',
            ['msg'=>$msg, 'params'=>$params]
        );

        return compact('code', 'msg', 'data');
    }


    /**
     * 验证 楼层数据
     * @param $params
     * @return array
     * @throws \Exception
     */
    function checkParams($params, $operation='add')
    {
        if (!in_array($operation, ['add','edit','del'])){
            throw new \Exception("验证未通过");
        }
        if (empty($params)){
            throw new \Exception("参数不能是空");
        }

        $data = [];
        if (in_array($operation, ['add','edit'])){
            $data['title'] = (string) ($params['title']??'');
            $data['icon'] = (string) ($params['icon']??'');
            $data['sort'] = (int)($params['sort']??0);
            $data['state'] = (int)($params['state']??0);
            $data['more_url'] = (string)($params['more_url']??'');
            $mainType = (string)($params['type']??'');
            if (empty($mainType)){
                throw new \Exception("type 不能是空");
            }
            $mainType = strtoupper($mainType);

            $mainTypeList = $this->mallMain -> getMainType();
            if (empty($mainTypeList)){
                throw new \Exception("type 配置错误，请联系管理员");
            }

            if (!array_key_exists($mainType, $mainTypeList)){
                throw new \Exception("type 错误");
            }
            $data['type'] = $mainType;

            $mainTurncount= $this->mallMain -> countMain(['state'=>1]);
            if ($data['state']==1 && $mainTurncount>10){
                throw new \Exception("可见楼层数已达到最大10层");
            }

            $count= $this->mallMain -> countMain(['type'=>$mainType, 'state'=>1]);

            switch ($mainType) {
                case MallMain::MAIN_TYPE_GOODS:
                    if ($data['state']==1 && $count>8){
                        throw new \Exception("该楼层可见楼层数已达到最大8层");
                    }
                    break;

                default:
                    break;
            }
        }

        if (in_array($operation, ['edit', 'del'])){
            $mainId = $params['id']??0;
            if ($mainId<=0){
                throw new \Exception("参数错误-ID");
            }
            $data['id'] = $mainId;
//            DB::enableQueryLog();
            //$info= $this->mallMain -> infoById($mainId);
            $ifExist= $this->mallMain -> countMain(['id'=>$mainId]);
//            dd(DB::getQueryLog());

            if (!$ifExist){
                throw new \Exception("该楼层或已删除");
            }
        }

        return $data;
    }

    public function delMain($params)
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        try {
            $checkParams = $this -> checkParams($params, 'del');
            $mainId = $checkParams['id'];
            DB::beginTransaction();
            // main 删除
            $this->mallMain -> delMain(['id'=>$mainId]);
            // item 删除
            $this->mallMain -> delItem(['main_id'=>$mainId]);
            DB::commit();

        } catch (\Exception $e) {
            DB::rollBack();
            $msg = $e->getMessage(). '-LINE:'. $e->getLine();
            $code = Hint::ERR_SYS_FAIL;
        }
        write_log(
            'MallMainServices'.(isCli()?'-cli':''),
            ($code!=0 ? '[ERROR]': '[INFO]') . '楼层删除',
            ['msg'=>$msg, 'params'=>$params]
        );

        return compact('code', 'msg', 'data');
    }


    /**
     * 添加楼层元素
     */
    public function addItem($params)
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        try {
            $checkParams = $this -> checkItemParams($params, 'add');
            $res = $this->mallMain -> addItem( $checkParams);
            if (!$res){
                throw new \Exception("楼层元素添加失败");
            }

        } catch (\Exception $e) {
            $msg = $e->getMessage(). '-LINE:'. $e->getLine();
            $code = Hint::ERR_SYS_FAIL;
        }
        write_log(
            'MallMainServices'.(isCli()?'-cli':''),
            ($code!=0 ? '[ERROR]': '[INFO]') . '楼层元素添加',
            ['msg'=>$msg, 'params'=>$params]
        );

        return compact('code', 'msg', 'data');
    }

    public function editItem($params)
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        try {

            $checkParams = $this -> checkItemParams($params, 'edit');
            $res = $this->mallMain -> editItem(['id'=>$checkParams['id']], $checkParams);
            if (!$res){
                throw new \Exception("楼层元素编辑失败");
            }

        } catch (\Exception $e) {
            $msg = $e->getMessage(). '-LINE:'. $e->getLine();
            $code = Hint::ERR_SYS_FAIL;
        }
        write_log(
            'MallMainServices'.(isCli()?'-cli':''),
            ($code!=0 ? '[ERROR]': '[INFO]') . '楼层元素编辑',
            ['msg'=>$msg, 'params'=>$params]
        );

        return compact('code', 'msg', 'data');
    }

    public function delItem($params)
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        try {
            $checkParams = $this -> checkItemParams($params, 'del');
            $itemId = $checkParams['id'];
            // item 删除
            $this->mallMain -> delItem(['id'=>$itemId]);
        } catch (\Exception $e) {
            $msg = $e->getMessage(). '-LINE:'. $e->getLine();
            $code = Hint::ERR_SYS_FAIL;
        }
        write_log(
            'MallMainServices'.(isCli()?'-cli':''),
            ($code!=0 ? '[ERROR]': '[INFO]') . '楼层删除',
            ['msg'=>$msg, 'params'=>$params]
        );

        return compact('code', 'msg', 'data');

    }

    public function checkItemParams($params, $operation='add'){

        if (!in_array($operation, ['add','edit','del'])){
            throw new \Exception("验证未通过");
        }
        if (empty($params)){
            throw new \Exception("参数不能是空");
        }
        $itemId = $params['id']??0;
        $data = [];
        if (in_array($operation, ['edit', 'add'])){
            $mainId = $params['main_id']??0;
            if ($mainId<=0){
                throw new \Exception("楼层Main ID不能是空");
            }
            $data['main_id'] = $mainId;

            $mainInfo = $this->mallMain -> infoMainById($mainId);

            if (empty($mainInfo)){
                throw new \Exception("楼层已删除，请退出刷新再次添加");
            }
            $mainType = $mainInfo['type'];

            $data['name'] = (string) ($params['name']??'');
            if (empty($data['name'])){
                throw new \Exception('name 必需');
            }
            $data['sort'] = (int) ($params['sort']??0);
            $data['is_show'] = (int) ($params['is_show']??1);
            $data['img'] = (string) ($params['img']??'');
            $data['start_time'] = (int) ($params['start_time']??0);
            $data['end_time'] = (int) ($params['end_time']??0);
            if ($data['start_time'] >= $data['end_time']){
                throw new \Exception("结束时间必需大于开始时间");
            }

            $content = [];
            switch ($mainType) {
                case MallMain::MAIN_TYPE_NAV:
                case MallMain::MAIN_TYPE_BANNER:

                    $itemTurnCount = $this->mallMain -> countItem(['id'=>$itemId]);
                    if ($data['is_show']==1 && $itemTurnCount>12){
                        throw new \Exception("该楼层数据最多可见12，请关闭部分数据后再次提交");
                    }

                    // 跳转地址
                    $link = (string) ($params['link']??'');
                    $content['link'] = $link;
                    break;

                case MallMain::MAIN_TYPE_GOODS:
                    $itemTurnCount = $this->mallMain -> countItem(['id'=>$itemId]);
                    if ($data['is_show']==1 && $itemTurnCount>30){
                        throw new \Exception("该楼层数据最多可见30，请关闭部分数据后再次提交");
                    }
                    // GID
                    $goods_id = $params['goods_id']??'';
                    if ($goods_id<=0){
                        throw new \Exception('goods_id 必需');
                    }
                    $content['goods_id'] = $goods_id;
                    break;

                default:
                    throw new \Exception("楼层类型暂不支持");
                    break;
            }
            $data['content'] = serialize($content);
        }


        if (in_array($operation, ['edit', 'del'])){
            if ($itemId<=0){
                throw new \Exception("参数错误-ID 必需");
            }
            $data['id'] = $itemId;

            $ifExist= $this->mallMain -> countItem(['id'=>$itemId]);
            if (!$ifExist){
                throw new \Exception("该元素或已删除");
            }
        }


        return $data;
    }


    /**
     * 楼层列表-后台调用
     * @param $params
     */
    public function listMain($params)
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        $where = [];
        $mainType = $params['type'] ?? '';
        if ($mainType){
            $where['type'] = $mainType;
        }
        if (isset($params['state']) && in_array($params['state'], [0,1])){
            $where['state'] = (int)$params['state'];
        }

        $list = $this->mallMain -> listMain($where);
        if ($list){
            $mainTypeList = $this->mallMain -> getMainType();
            foreach ($list as $key => &$value){
                $value['type_name'] = $mainTypeList[$value['type']]??'';
            }
        }

        $data['list'] = $list;

        return compact('code', 'msg', 'data');
    }
    /**
     * 楼层列表-后台调用
     * @param $params
     */
    public function listItem($params)
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        try {
            $where = [];

            $mainId = $params['main_id'] ?? '';
            if ($mainId<=0){
                throw new \Exception('参数必需 Main ID');
            }

            $mainInfo = $this->mallMain -> infoMainById($mainId);
            if (empty($mainInfo)){
                throw new \Exception('未找到楼曾数据');
            }
            $MainType = $mainInfo['type'];

            $where['main_id'] = $mainId;
            $list = $this->mallMain -> listItem($where);
            $initItem = [];
            if ($list){
                foreach ($list as $key => $value){
                    $value['start_date'] = $value['start_time'] ? date('Y-m-d H:i:s', $value['start_time']) : '';
                    $value['end_date'] = $value['end_time'] ? date('Y-m-d H:i:s', $value['end_time']) : '';

                    switch ($MainType) {
                        case MallMain::MAIN_TYPE_GOODS:
                            $initData = $this->initItemGoodsData($value);
                            if ($initData){
                                array_push($initItem, $initData);
                            }
                            break;

                        case MallMain::MAIN_TYPE_BANNER:
                        case MallMain::MAIN_TYPE_NAV:
                            $initData = $this->initItemNannerData($value);
                            if ($initData){
                                array_push($initItem, $initData);
                            }
                            break;

                        default:
                            break;
                    }
                }
            }

            $data['list'] = $initItem;
        } catch (\Exception $e) {
            $msg = $e->getMessage(). '-LINE:'. $e->getLine();
            $code = Hint::ERR_SYS_FAIL;
        }

        return compact('code', 'msg', 'data');
    }



    /**
     * 获取楼层完整数据 - 客户端调用
     * @param $params
     */
    public function getMallMain($params)
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        $userId = $params['user_id'];


        // 1、获取楼层数据
        // 2、获取 元素数据
        // 3、楼层类型-整理数据
        $mail = $this->mallMain -> getMallMain();
        if ($mail){
            # 用户炫酷值等级
            /*$this->UserCoolvalServices  = new UserCoolvalServices();
            $resUserCoolInfo = $this->UserCoolvalServices -> getUserCoolInfo($userId);
            if ($resUserCoolInfo && $resUserCoolInfo['data']){
                $UserCoolInfo = [];
                $UserCoolInfo['cool_val'] = $resUserCoolInfo['data']['cool_val'] ?? 0;
                $UserCoolInfo['level_info'] = $resUserCoolInfo['data']['level_info'] ?? 0;

                $this -> UserCoolInfo = $UserCoolInfo;
            }*/
            $extend = [];
            $extend['goods_show'] = 1;
            foreach ((array)$mail as $key => $mailVal) {
                $MainType = $mailVal['type']??'';
                $MainId = $mailVal['id'];
                if (!$MainType){
                    continue;
                }
                $mailVal['icon_url'] = build_image($mailVal['icon']);
                $item = $this->mallMain -> getMainItem($MainId);
                if (empty($item)){
                    continue;
                }
                $initItem = $this -> initItemData($MainType, $item, $extend);
                $mailVal['item'] = $initItem;
                if ($initItem){
                    array_push($data, $mailVal);
                }
            }
        }

        return compact('code', 'msg', 'data');
    }

    /**
     * 整理数据
     * @param $MainType
     * @param $item
     * @return false
     */
    public function initItemData($MainType, array $item, $extend=[])
    {
        if (empty($MainType)){
            return false;
        }
        if (empty($item)){
            return false;
        }
        $data = [];
        foreach ($item as $k => $itemVal) {
            switch ($MainType) {
                case MallMain::MAIN_TYPE_GOODS:
                    $goodsItemRes = $this->initItemGoodsData($itemVal, $extend);
                    if ($goodsItemRes){
                        $data[] = $goodsItemRes;
                    }
                    break;

                case MallMain::MAIN_TYPE_BANNER:
                case MallMain::MAIN_TYPE_NAV:
                    $data[] = $this->initItemNannerData($itemVal);

                    break;

                default:
                    break;
            }
        }

        return $data;

    }

    private function initItemNannerData(array $item){
        if ($item){
            $content = unserialize($item['content']);
            $item['content'] = $content ?: '';
            $item['img_url'] = build_image($item['img']);
        }
        return $item;
    }

    private function initItemGoodsData(array $item, $extend=[]){
        if ($item){
            $content = unserialize($item['content']);
            $goods_id = $content['goods_id']??0;
            if (empty($goods_id)){
                return false;
            }
            $model_mall = new Mall();
            $is_show = $extend['goods_show'] ?? 0;
            $good = $model_mall->get_goods($goods_id ,$is_show);
            if (empty($good)){
                return false;
            }

            // 礼物等级
            $level = $good['level']??0;
            $levelInfo = [];
            if ($level){
                $levelResule = (new GoodsLevelServices())->getGoosLevelList();
                if ($levelResule && $levelList =$levelResule['data']){
                    $levelInfo = array_column($levelList, NULL, 'level');
                }
            }
            $good['level_info'] = $levelInfo[$level] ?? ['empty'=>null];

            // 可升级礼物配置
            $is_upgrade = $good['is_upgrade'];
            $upgradeConfig = [];
            if ($is_upgrade){
                $upgradeConfig = $model_mall->getGoodsUpConfig($goods_id);
                if ($upgradeConfig){
                    foreach ($upgradeConfig as $k => $val){
                        $upgradeConfig[$k]['img'] = build_image($val['img']);
                        $upgradeConfig[$k]['animate'] = build_image($val['animate']);
                    }
                }

                //$UserCoolInfo = $this -> UserCoolInfo;
/*
                // 获取用户 该商品等级
                $GoodsIncomeServise = new GoodsIncomeServices();
                $userService = new UserServices();
                $userInfo = $userService->get_current_user();
                $userId = $userInfo ? ($userInfo['user_id'] ?? 0) : 0;
                $userUpgradeLevel = 0;
                $upgradeInfo = $GoodsIncomeServise->getUserGoodsUpgradeInfo($userId, $goods_id);
                print_r($upgradeInfo);die();
*/
            }
            // 情侣商品
            $give_goods_info = [];
            $give_data_id = $good['give_data_id'] ?? 0;
            if ($give_data_id){
                $give_good = $model_mall->get_goods($give_data_id ,0);
                if ($give_good && $give_good['give_data_id'] == $goods_id ){
                    $give_good['level_info'] = $levelInfo[$give_good['level']] ?? ['empty'=>null];
                    // 情侣商品相互绑定 有效，否则视为普通商品
                    $give_goods_info = $give_good;
                }
            }

            $good['give_goods_info'] = (object)$give_goods_info;
            $good['upgrade_config'] = $upgradeConfig;
            //$good['user_cool_info'] = (object)$UserCoolInfo;

            $item['content'] = $good;
            $item['img_url'] = build_image($item['img']);
        }
        return $item;
    }




}
